package com.xiye.system.controller.user;

import java.io.FileInputStream;
import java.util.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.xiye.common.entity.Page;
import com.xiye.common.entity.Result;
import com.xiye.common.entity.Role;
import com.xiye.common.util.*;
import com.xiye.common.util.mail.SimpleMailSender;
import com.xiye.system.config.YmlConfig;
import com.xiye.system.service.role.RoleService;
import io.swagger.annotations.*;
import net.sf.json.JSONArray;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import com.xiye.common.controller.BaseController;
import com.xiye.system.service.user.UserService;
import com.xiye.common.entity.PageData;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 西野
 * @version V1.0
 * @title UserController.java
 * @package com.xiye.controller.system.user
 * @description 系统用户
 * @date 2018-07-11
 */
@RestController
@Api(value = "/user", tags = "用户管理")
@RequestMapping(value = "/user")
@SuppressWarnings({"rawtypes", "unchecked"})
public class UserController extends BaseController {

    String menuUrl = Const.MENU_USER; // 菜单地址(权限用)
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private YmlConfig ymlConfig;

    /*
     * @Author 西野
     * @Date 2018-07-20 10:46:33
     * @Description 显示用户列表
     * @Param [page]
     * @Return java.lang.Object
     */
    @ApiOperation(value = "显示用户列表", notes = "显示系统用户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "ROLE_ID", value = "根据传输的数值显示列表数据", required = true), @ApiImplicitParam(name = "keywords", value = "过滤条件文本框"), @ApiImplicitParam(name = "lastLoginStart", value = "开始时间yyyy-mm-dd hh24:mi:ss"), @ApiImplicitParam(name = "lastLoginEnd", value = "结束时间yyyy-mm-dd hh24:mi:ss"), @ApiImplicitParam(name = "showCount", value = "每页显示记录数"), @ApiImplicitParam(name = "totalPage", value = "总页数"), @ApiImplicitParam(name = "totalResult", value = "总记录数"), @ApiImplicitParam(name = "currentPage", value = "当前页"), @ApiImplicitParam(name = "currentResult", value = "当前记录起始索引"), @ApiImplicitParam(name = "entityOrField", value = "true:需要分页的地方，传入的参数就是Page实体；false:需要分页的地方，传入的参数所代表的实体拥有Page属性")})
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "服务器异常")})
    @RequestMapping(value = "/listUsers", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result listUsers(Page page) throws Exception {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String keywords = pd.getString("keywords"); // 关键词检索条件
        if (null != keywords && !"".equals(keywords)) {
            pd.put("keywords", keywords.trim());
        }
        page.setPageData(pd);
        List<PageData> userList = userService.listUsers(page); // 列出用户列表
        pd.put("ROLE_ID", "1");
        List<Role> roleList = roleService.listAllRolesByPId(pd);// 列出所有系统用户角色
        map.put("userList", JSONArray.fromObject(userList));
        map.put("roleList", JSONArray.fromObject(roleList));
        map.put("pd", pd);
        map.put("Page", page);
        map.put("QX", Jurisdiction.getHC()); // 按钮权限
        return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 13:05:26
     * @Description 新增用户
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "新增用户", notes = "新增用户")
    @ApiImplicitParams({@ApiImplicitParam(name = "USERNAME", value = "登录名", required = true), @ApiImplicitParam(name = "PASSWORD", value = "密码", required = true), @ApiImplicitParam(name = "NAME", value = "姓名", required = true), @ApiImplicitParam(name = "ROLE_ID", value = "角色ID", required = true), @ApiImplicitParam(name = "ROLE_IDS", value = "副职角色；数据形式存储。例：id1，id2", required = true), @ApiImplicitParam(name = "STATUS", value = "状态；0：默认开启；1：冻结", required = true), @ApiImplicitParam(name = "BZ", value = "备注", required = true), @ApiImplicitParam(name = "EMAIL", value = "邮箱", required = true), @ApiImplicitParam(name = "PHONE", value = "电话", required = true)})
    @RequestMapping(value = "/addUser", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result addUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        pd.put("USER_ID", this.get32UUID()); // ID 主键
        pd.put("LAST_LOGIN", ""); // 最后登录时间
        pd.put("IP", ""); // IP
        pd.put("STATUS", "0"); // 状态
        pd.put("RIGHTS", "");
        pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString()); // 密码加密
        try {
            if (null == userService.findByUsername(pd)) { // 判断用户名是否存在
                userService.addUser(pd); // 执行保存
                return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
            } else {
                return ResultUtil.setRowbackResut_entity(false, 200, "已存在该用户", map);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 13:54:29
     * @Description 删除用户
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "删除用户", notes = "根据USER_ID删除用户")
    @ApiImplicitParam(name = "USER_ID", value = "用户id", required = true)
    @RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public Result deleteUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        try {
            userService.deleteUser(pd);
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 13:40:11
     * @Description 修改用户
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "修改用户", notes = "根据USER_ID修改用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "USERNAME", value = "登录名", required = true), @ApiImplicitParam(name = "PASSWORD", value = "密码", required = true), @ApiImplicitParam(name = "NAME", value = "姓名", required = true), @ApiImplicitParam(name = "ROLE_ID", value = "角色ID", required = true), @ApiImplicitParam(name = "ROLE_IDS", value = "副职角色；数据形式存储。例：id1，id2", required = true), @ApiImplicitParam(name = "STATUS", value = "状态；0：默认开启；1：冻结", required = true), @ApiImplicitParam(name = "BZ", value = "备注", required = true), @ApiImplicitParam(name = "EMAIL", value = "邮箱", required = true), @ApiImplicitParam(name = "PHONE", value = "电话", required = true), @ApiImplicitParam(name = "USER_ID", value = "用户主键ID", required = true)})
    @RequestMapping(value = "/editUser", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result editUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        try {


            if (!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))) { // 如果当前登录用户修改用户资料提交的用户名非本人
                //if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
                //    return null;
                //}  判断当前操作者有无用户管理查看权限
                //if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
                //    return null;
                //} 判断当前操作者有无用户管理修改权限
                if ("admin".equals(pd.getString("USERNAME")) && !"admin".equals(Jurisdiction.getUsername())) {
                    return null;
                } // 非admin用户不能修改admin
            } else { // 如果当前登录用户修改用户资料提交的用户名是本人，则不能修改本人的角色ID
                pd.put("ROLE_ID", userService.findByUsername(pd).getString("ROLE_ID")); // 对角色ID还原本人角色ID
                pd.put("ROLE_IDS", userService.findByUsername(pd).getString("ROLE_IDS")); // 对角色ID还原本人副职角色ID
            }
            if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))) {
                pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
            }
            userService.editUser(pd); // 执行修改
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 13:49:36
     * @Description 查看用户
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "查看用户", notes = "根据USERNAME查询用户")
    @ApiImplicitParam(name = "USERNAME", value = "用户登录名", required = true)
    @RequestMapping(value = "/queryUser", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result queryUser() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String USERNAME = pd.getString("USERNAME");
        try {
            if ("admin".equals(USERNAME)) {
                return ResultUtil.setRowbackResut_entity(false, 200, "不能查看admin用户", map);
            } // 不能查看admin用户
            pd.put("ROLE_ID", "1");
            List<Role> roleList = roleService.listAllRolesByPId(pd); // 列出所有系统用户角色
            pd = userService.findByUsername(pd); // 根据ID读取
            if (null == pd) {
                PageData rpd = new PageData();
                rpd.put("RNUMBER", USERNAME); // 用户名查不到数据时就把数据当作角色的编码去查询角色表(工作流的待办人物，查看代办人资料时用到)
                rpd = roleService.getRoleByRnumber(rpd);
                map.put("rpd", rpd);
            }
            map.put("pd", pd);
            map.put("roleList", JSONArray.fromObject(roleList));
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 14:28:25
     * @Description 批量删除
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "批量删除用户", notes = "根据USER_ID数组删除用户")
    @ApiImplicitParam(name = "USER_IDS", value = "用户USER_IDS", required = true)
    @RequestMapping(value = "/deleteAllUser", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public Result deleteAllUser() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        try {
            String USER_IDS = pd.getString("USER_IDS");
            if (null != USER_IDS && !"".equals(USER_IDS)) {
                String ArrayUSER_IDS[] = USER_IDS.split(",");
                userService.deleteAllUser(ArrayUSER_IDS);
                return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
            } else {
                return ResultUtil.setRowbackResut_entity(false, 200, ymlConfig.getServer_error(), map);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 15:01:45
     * @Description 导出用户信息到Excel
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "导出用户信息", notes = "导出用户信息到Excel")
    @ApiImplicitParam(name = "keywords", value = "过滤条件文本框")
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result exportExcel(HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "toExcel")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        String keywords = pd.getString("keywords"); // 关键词检索条件
        if (null != keywords && !"".equals(keywords)) {
            pd.put("keywords", keywords.trim());
        }
        List<PageData> varOList = userService.listAllUser(pd);
        List<PageData> varList = new ArrayList<PageData>();
        String model = "Users.xlsx";
        Integer title_size = 7;
        Integer s = 2;
        FileInputStream fs = new FileInputStream(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + Const.EXCELMODEL + model));
        // 读取excel模板
        XSSFWorkbook workbook = new XSSFWorkbook(fs);
        // 读取了模板内所有sheet内容
        XSSFSheet sheet = workbook.getSheetAt(0);
        Tools.forEach(varOList, (index, v) -> {
            PageData vpd = new PageData();
            vpd.put("var1", String.valueOf(index + 1)); // 1
            vpd.put("var2", String.valueOf(v.getString("USERNAME"))); // 2
            vpd.put("var3", String.valueOf(v.getString("SERIAL_NUMBER"))); // 3
            vpd.put("var4", String.valueOf(v.getString("NAME"))); // 4
            vpd.put("var5", String.valueOf(v.getString("ROLE_NAME"))); // 5
            vpd.put("var6", String.valueOf(v.getString("PHONE"))); // 6
            vpd.put("var7", String.valueOf(v.getString("EMAIL"))); // 7
            //vpd.put("var8", String.valueOf(varOList.get(i).getString("LAST_LOGIN"))); // 8
            //vpd.put("var9", String.valueOf(varOList.get(i).getString("IP"))); // 9
            varList.add(vpd);
        });

        for (int i = 0; i < varOList.size(); i++) {
            XSSFRow row = sheet.createRow(i + s);
            for (int j = 0; j < title_size; j++) {
                PageData vpd = varList.get(i);
                String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : "";
                XSSFCell cell = row.createCell(j);
                cell.setCellValue(varstr);// 设置单元格内容
                XSSFCellStyle wrapStyle = workbook.createCellStyle();
                wrapStyle.setWrapText(true); // 设置单元格内容是否自动换行
                /*
                 * poi 3.16
                 *
                 * wrapStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 设置单元格内容水平居中
                 * wrapStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 设置单元格内容垂直居中
                 * wrapStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
                 * wrapStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);// 下边框
                 * wrapStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
                 * wrapStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
                 */

                /*
                 * poi 3.17
                 */
                wrapStyle.setAlignment(HorizontalAlignment.CENTER); // 设置单元格内容水平居中
                wrapStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格内容垂直居中
                wrapStyle.setBorderTop(BorderStyle.THIN);// 上边框
                wrapStyle.setBorderBottom(BorderStyle.THIN);// 下边框
                wrapStyle.setBorderLeft(BorderStyle.THIN);// 左边框
                wrapStyle.setBorderRight(BorderStyle.THIN);// 右边框
                cell.setCellStyle(wrapStyle);
            }
        }
        // 如果这行没有了，整个公式都不会有自动计算的效果的
        sheet.setForceFormulaRecalculation(true);
        Date date = new Date();
        String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        workbook.close();
        out.flush();
        out.close();
        return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
    }

    /*
     * @Author 西野
     * @Date 2018-07-20 16:08:53
     * @Description 下载模版
     * @Param [response]
     * @Return void
     */
    @ApiOperation(value = "下载模版", notes = "下载用户Excel模板")
    @RequestMapping(value = "/downExcel", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public void downExcel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, (Const.EXCELMODEL + "Users.xlsx"), "Users.xlsx");
    }

    /*
     * @Author 西野
     * @Date 2018-07-21 11:37:00
     * @Description 从EXCEL导入到数据库
     * @Param [file]
     * @Return java.lang.Object
     */
    @ApiOperation(value = "导入用户信息", notes = "从EXCEL导入到数据库")
    @ApiImplicitParam(name = "excel", value = "Excel文件")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result importExcel(@RequestParam(value = "excel", required = false) MultipartFile file) throws Exception {
        PageData pd = new PageData();
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        try {
            if (null != file && !file.isEmpty()) {
                String filePath = Const.EXCELMODEL; // 文件上传路径
                String fileName = FileUpload.fileUp(file, filePath, "Users"); // 执行上传
                List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0); // 执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
                /* 存入数据库操作====================================== */
                pd.put("RIGHTS", ""); // 权限
                pd.put("IP", ""); // IP
                pd.put("STATUS", "0"); // 状态
                pd.put("ROLE_ID", "1");
                List<Role> roleList = roleService.listAllRolesByPId(pd);// 列出所有系统用户角色
                pd.put("ROLE_ID", roleList.get(0).getROLE_ID()); // 设置角色ID为随便第一个
                /**
                 * var0 :编号 var1 :姓名 var2 :手机 var3 :邮箱 var4 :备注
                 */
                listPd.forEach(l -> {
                    try {
                        pd.put("USER_ID", this.get32UUID()); // ID
                        String USERNAME = GetPinyin.getPingYin(l.getString("var1")); // 根据姓名汉字生成全拼
                        pd.put("USERNAME", USERNAME);
                        pd.put("SERIAL_NUMBER", l.getString("var2")); // 编号已存在就跳过
                        pd.put("NAME", l.getString("var3")); // 姓名
                        if (userService.findByUsername(pd) != null) { // 判断用户名是否重复
                            USERNAME = GetPinyin.getPingYin(l.getString("var1")) + Tools.getRandomNum();
                            pd.put("USERNAME", USERNAME);
                        }
                        pd.put("BZ", l.getString("var4")); // 备注
                        pd.put("PHONE", l.getString("var5")); // 手机号
                        //if (Tools.checkEmail(listPd.get(i).getString("var6"))) { // 邮箱格式不对就跳过
                        pd.put("EMAIL", l.getString("var6"));
                        //if (userService.findByUE(pd) != null) { // 邮箱已存在就跳过
                        //    continue;
                        //}
                        //} else {
                        //    continue;
                        //}
                        pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123456").toString()); // 默认密码123456
                        //if (userService.findByUN(pd) != null) {
                        //    continue;
                        //}

                        /* 存入数据库操作====================================== */
                        userService.addUser(pd);
                    } catch (Exception e) {
                        logger.error(e.toString(), e);
                    }
                });
            } else {
                return ResultUtil.setRowbackResut_entity(false, 200, ymlConfig.getServer_success(), map);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
        return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
    }


    /*
     * @Author 西野
     * @Date 2018-07-21 11:50:17
     * @Description 发送电子邮件
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "发送邮件", notes = "发送电子邮件")
    @ApiImplicitParams({@ApiImplicitParam(name = "TITLE", value = "邮件标题", required = true), @ApiImplicitParam(name = "CONTENT", value = "邮件内容", required = true), @ApiImplicitParam(name = "isAll", value = "是否全体成员发送yes/no", required = true), @ApiImplicitParam(name = "EMAIL", value = "邮箱--多邮箱例子：123@qq.com;456@qq.com", required = true), @ApiImplicitParam(name = "TYPE", value = "类型--1：纯文本；2：带标签", required = true)})
    @RequestMapping(value = "/sendEmail", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result sendEmail() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "email")) {
            return ResultUtil.setRowbackResut_entity(false, 403, ymlConfig.getAuthorization(), map);
        }
        PageData pd = this.getPageData();
        int count = 0; // 统计发送成功条数
        int zcount = 0; // 理论条数
        //String strEMAIL = Tools.readTxtFile(Const.EMAIL); // 读取邮件配置
        String strEMAIL = "smtp.qq.com,587,89085055@qq.com,cfpqrbrjzsqgcadd"; // 读取邮件配置
        List<PageData> pdList = new ArrayList<PageData>();
        String toEMAIL = pd.getString("EMAIL"); // 对方邮箱
        String TITLE = pd.getString("TITLE"); // 标题
        String CONTENT = pd.getString("CONTENT"); // 内容
        String TYPE = pd.getString("TYPE"); // 类型
        String isAll = pd.getString("isAll"); // 是否发送给全体成员 yes or no

        if (null != strEMAIL && !"".equals(strEMAIL)) {
            String strEM[] = strEMAIL.split(",");
            if (strEM.length == 4) {
                if ("yes".endsWith(isAll)) {
                    try {
                        List<PageData> userList = new ArrayList<PageData>();
                        userList = userService.listAllUser(pd);
                        zcount = userList.size();
                        try {
                            for (int i = 0; i < userList.size(); i++) {
                                if (Tools.checkEmail(userList.get(i).getString("EMAIL"))) { // 邮箱格式不对就跳过
                                    SimpleMailSender.sendEmail(strEM[0], strEM[1], strEM[2], strEM[3], userList.get(i).getString("EMAIL"), TITLE, CONTENT, TYPE);// 调用发送邮件函数
                                    count++;
                                } else {
                                    continue;
                                }
                            }
                            map.put("count", count); // 成功数
                            map.put("ecount", zcount - count); // 失败数
                            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
                        } catch (Exception e) {
                            logger.error(e.toString(), e);
                            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
                        }
                    } catch (Exception e) {
                        logger.error(e.toString(), e);
                        return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
                    }
                } else {
                    toEMAIL = toEMAIL.replaceAll("；", ";");
                    toEMAIL = toEMAIL.replaceAll(" ", "");
                    String[] arrTITLE = toEMAIL.split(";");
                    zcount = arrTITLE.length;
                    try {
                        for (int i = 0; i < arrTITLE.length; i++) {
                            if (Tools.checkEmail(arrTITLE[i])) { // 邮箱格式不对就跳过
                                SimpleMailSender.sendEmail(strEM[0], strEM[1], strEM[2], strEM[3], arrTITLE[i], TITLE, CONTENT, TYPE);// 调用发送邮件函数
                                count++;
                            } else {
                                continue;
                            }
                        }
                        map.put("count", count); // 成功数
                        map.put("ecount", zcount - count); // 失败数
                        return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
                    } catch (Exception e) {
                        logger.error(e.toString(), e);
                        return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
                    }
                }
            } else {
                return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
            }
        } else {
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }
}
